import {getSign} from "./util.js";
import {formatDate} from "./time.js";

const cookieName = "tokenInfo";

export const clearOutSizeSession = () => {
    // 清除薪酬相关信息
    localStorage.removeItem("login");
    localStorage.removeItem("ticket");
    localStorage.removeItem("userInfo");
    localStorage.removeItem("menuInfo");
    // 清除易天相关信息
    localStorage.removeItem("ACCESS_TOKEN");
    localStorage.removeItem("REFRESH_TOKEN");
    sessionStorage.removeItem("ACCESS_TOKEN");
    sessionStorage.removeItem("REFRESH_TOKEN");
    // 清除自助挖掘登录信息
    localStorage.removeItem("Access-Token")
}

export const getTokenInfo = function(cookieFieldName, { isJson = true } = {}) {
    var name = cookieFieldName || cookieName;
    var tokenInfo = null;
    var arr,
        reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)"); //正则匹配
    if ((arr = document.cookie.match(reg))) {
        tokenInfo = unescape(arr[2]);
    }
    // if (typeof tokenInfo == "undefined") {
    //     tokenInfo = {};
    // } else {
    //     tokenInfo = JSON.parse(tokenInfo);
    // }
    if (isJson) {
        try {
            tokenInfo = JSON.parse(tokenInfo);
        } catch (error) {
            tokenInfo = null;
        }
    }
    return tokenInfo;
};
window.getTokenInfo = getTokenInfo;

export const setSessionCookie = function(
    value,
    { cookiePath, cookieFieldName } = {}
) {
    var name = cookieFieldName || cookieName;
    var userAgent = navigator.userAgent; //取得浏览器的userAgent字符串
    var isIE =
        userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1; //判断是否IE<11浏览器
    var isEdge = userAgent.indexOf("Edge") > -1 && !isIE; //判断是否IE的Edge浏览器
    var isIE11 =
        userAgent.indexOf("Trident") > -1 && userAgent.indexOf("rv:11.0") > -1;

    var expire = "";
    var path = "; path=/";
    //var path ="";
    if (value) {
        if (isIE || isEdge || isIE11) {
            expire = "; expires=At the end of the Session";
        } else {
            expire = "; expires=Session";
        }
    } else {
        expire = ";expires=Thu, 01 Jan 1970 00:00:00 GMT";
    }

    if (cookiePath != null) {
        path = "; path=" + cookiePath;
    }
    document.cookie = name + "=" + escape(value) + expire + path;
};

export const setSessionByRefreshTokenInfo = (data) => {
    if(!data) return;
    let tokenInfo = getTokenInfo() || {};
    if(!tokenInfo) return;

    let newAccessToken = data.access_token;
    let newRefreshToken = data.refresh_token;

    tokenInfo.refresh_token = newRefreshToken;
    tokenInfo.access_token = newAccessToken;

    // 设置综合token
    let cmsToken = {
        accesstoken: newAccessToken,
        staffId: tokenInfo.staff_id,
        timestamp: formatDate(new Date().getTime(), 'yyyyMMDDHHmmssSSS'),
    }
    cmsToken.sign = getSign(cmsToken);

    // 互联网token
    let innerToken = {
        staffId: tokenInfo.staff_id,
        token: `cms_${newAccessToken}`,
        access_token: newAccessToken
    }
    setSessionCookie(JSON.stringify({...tokenInfo,...cmsToken})); // 设置tokenInfo
    
    Object.keys(cmsToken).forEach(k => {
        setSessionCookie(cmsToken[k], {
            cookieFieldName: k,
        });
    })
    Object.keys(innerToken).forEach(k => {
        setSessionCookie(innerToken[k], {
            cookieFieldName: k,
        });
    })
    setSessionCookie(new Date().getTime(), {
        cookieFieldName: 'tokenTime',
    });
} 
window.setSessionByRefreshTokenInfo = setSessionByRefreshTokenInfo;

